/*
 * @copyright: Huang Ding
 * @Author: ding-cx
 * @Date: 2021-02-26 16:57:25
 * @LastEditors: ding-cx
 * @LastEditTime: 2021-03-16 13:36:51
 * @Description: file content
 */
import { Application } from "egg";
import { DataTypes, Model } from "sequelize";
import { modelCommonField } from "../../utils";

export interface roleInterface extends Model {
  /** 主键id */
  id: number;
  /** 角色名 */
  role_name: string;
  /** 备注 */
  memo: string;
  /** 创建者id */
  create_user_id: number;
  /** 修改者id */
  edit_user_id: number;
}

export default (app: Application) => {
  const model = app.model.define<roleInterface>(
    app.config.dbModel_prefix + "sys_role",
    {
      role_name: {
        field: "role_name",
        comment: "角色名",
        type: DataTypes.STRING(16),
      },
      memo: {
        field: "memo",
        comment: "备注",
        type: DataTypes.STRING(80),
      },
      ...modelCommonField,
    }
  );
  // egg-sequelize绑定关联关系的方法。
  (model as any).associate = () => {
    // 关联创建者。
    model.belongsTo(app.model.Sys.User, {
      foreignKey: "create_user_id",
      as: "create_user",
      constraints: false,
    });
    // 关联修改者。
    model.belongsTo(app.model.Sys.User, {
      foreignKey: "edit_user_id",
      as: "edit_user",
      constraints: false,
    });
    // 关联角色的权限列表
    model.hasMany(app.model.Sys.RolePermission, {
      foreignKey: "role_id",
      as: "role_permission",
      constraints: false,
    });
  };
  return model;
};
